package Jwt快速入门;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class JWTDemo {
    public static void main(String[] args) {
        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

        // 生成 Token
        String token = generateToken(key);
        System.out.println("Generated Token: " + token);

        // 解密 Token
//        token="eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0NHUzYWk1cCIsInVzZXJJZCI6MTczNDUxMDQwMjA4NTc2MTAyNSwiZXhwIjoxNzAyMzc3NTY2fQ.ieS1ewwTcepIw69lztYy2yBXYg4WrZ3dJs6RHIqyWSE";
//       token="eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0NHUzYWk1cCIsInVzZXJJZCI6MTczNDUxMDQwMjA4NTc2MTAyNSwiZXhwIjoxNzAyMzc4MjY1fQ.Fpp6q5fDFJllGnZB8uCDxGsku856koSSXbaxNhW3VdY"
        Claims claims = parseToken(token, key);
        System.out.println("Decoded Claims:");
        System.out.println("ID: " + claims.getId());
        System.out.println("Subject: " + claims.getSubject());
        System.out.println("Issued At: " + claims.getIssuedAt());
        System.out.println("Expiration: " + claims.getExpiration());
    }

    private static String generateToken(Key key) {
        return Jwts.builder()
                .setId("007")
                .setSubject("小马")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)))
                .signWith(key)
                .compact();
    }

    private static Claims parseToken(String token, Key key) {
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}

